<template>
  <div class="InventoryDamage">
    <div class="InventoryDamage-search">
      <div class="InventoryDamage-search-left">
        <div class="InventoryDamage-search-item">
          <div class="InventoryDamage-search-item-label">商品名</div>
          <el-input v-model="searchForm.productName" class="InventoryDamage-search-item-input"
                    placeholder="请输入商品名称"
                    clearable/>
        </div>
        <div class="InventoryDamage-search-item">
          <div class="InventoryDamage-search-item-label">商品类型</div>
          <el-tree-select v-model="searchForm.categoryId" :data="categoryTreeData" :render-after-expand="false"
                          :props="{ value: 'id', label: 'name', children: 'children' }"
                          class="InventoryDamage-search-item-input" placeholder="选择分类" check-strictly clearable/>
        </div>
        <div class="InventoryDamage-search-item">
          <div class="InventoryDamage-search-item-label">时间范围</div>
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至"
                          start-placeholder="开始日期" end-placeholder="结束日期" unlink-panels
                          :shortcuts="dateShortcuts" class="InventoryDamage-search-item-input"/>
        </div>
      </div>
      <div class="InventoryDamage-search-right">
        <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="danger" icon="Remove" @click="openSelectProduct">报损</el-button>
      </div>
    </div>

    <div class="InventoryDamage-table">
      <el-table :data="tableData.list" class="InventoryDamage-table-main" border stripe v-loading="loading">
        <el-table-column type="index" :index="computeIndex" label="序号" width="60" align="center"/>
        <el-table-column prop="date" label="日期" width="120" align="center"/>
        <el-table-column prop="productCode" label="商品编码" width="140" align="center"/>
        <el-table-column prop="name" label="商品名称" min-width="160" align="center"/>
        <el-table-column prop="unit" label="单位" width="100" align="center"/>
        <el-table-column prop="quantity" label="数量" width="120" align="center">
          <template #default="{row}">
            <span class="text-danger">{{ toFixed(row.quantity) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="note" label="备注" min-width="160" align="center">
          <template #default="{row}">{{ row.note || '-' }}</template>
        </el-table-column>
        <el-table-column prop="userName" label="操作用户" width="140" align="center"/>
      </el-table>
    </div>

    <div class="InventoryDamage-pagination">
      <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10,20,50]"
          :total="tableData.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="InventoryDamage-pagination-main"
      />
    </div>

    <!-- 复用通用商品选择弹窗 -->
    <ProductSelectDialog v-model:visible="selectVisible" @selected="handleProductSelected"/>
    <AdjustItemDialog v-model:visible="adjustVisible" mode="damage" :product-id="currentProductId"
                      @confirm="handleAdjustConfirm"/>
  </div>
</template>
<script setup>
import {ref, reactive, onMounted, watch} from 'vue'
import ProductSelectDialog from '../../../../components/ProductSelectDialog.vue'
import AdjustItemDialog from '../AdjustItemDialog.vue'
import {listInventoryDetails} from '../../../../api/inventoryDetailApi.js'
import {getCategoriesTree} from '../../../../api/categoryApi.js'
import {addInventoryDetail} from "../../../../api/inventoryDetailApi.js";
import {ElMessage} from 'element-plus'

// 分类数据从接口获取
const categoryTreeData = ref([])

const dateShortcuts = [
  {
    text: '最近7天', value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 6);
      return [start, end]
    }
  },
  {
    text: '本月', value: () => {
      const d = new Date();
      const start = new Date(d.getFullYear(), d.getMonth(), 1);
      const end = new Date(d.getFullYear(), d.getMonth() + 1, 0);
      return [start, end]
    }
  }
]
const thisMonthRange = () => {
  const d = new Date();
  return [new Date(d.getFullYear(), d.getMonth(), 1), new Date(d.getFullYear(), d.getMonth() + 1, 0)]
}

const searchForm = reactive({productName: '', categoryId: null, startDate: '', endDate: '', dateRange: []})
const pagination = ref({pageNum: 1, pageSize: 10})
const tableData = ref({list: [], total: 0})
const loading = ref(false)

const selectVisible = ref(false)
const adjustVisible = ref(false)
const currentProductId = ref(null)

// 工具函数
const toFixed = (v) => Number(v || 0).toFixed(2)
const money = (v) => Number(v || 0).toFixed(2)
const formatDate = (date) => {
  if (!date) return '';
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return `${y}-${m}-${d}`
}

watch(() => searchForm.dateRange, (val) => {
  if (Array.isArray(val) && val.length === 2 && val[0] && val[1]) {
    searchForm.startDate = formatDate(new Date(val[0]))
    searchForm.endDate = formatDate(new Date(val[1]))
  } else {
    searchForm.startDate = ''
    searchForm.endDate = ''
  }
})

const loadData = async () => {
  loading.value = true
  try {
    const condition = {
      productName: searchForm.productName?.trim() || undefined,
      categoryId: searchForm.categoryId || undefined,
      operationType: 'damage',
      startDate: searchForm.startDate || undefined,
      endDate: searchForm.endDate || undefined
    }
    const params = {pageNum: pagination.value.pageNum, pageSize: pagination.value.pageSize, condition}
    const res = await listInventoryDetails(params) // 期望结构 { list:[], total:0 }
    tableData.value = {list: (res?.list || []).map(mapRecord), total: res?.total || 0}
  } catch (e) {
  } finally {
    loading.value = false
  }
}

// 加载分类树
const loadCategoryTree = async () => {
  try {
    const res = await getCategoriesTree()
    if (res && typeof res === 'object' && !Array.isArray(res)) {
      categoryTreeData.value = [res]
    } else if (Array.isArray(res)) {
      categoryTreeData.value = res
    } else {
      categoryTreeData.value = []
    }
  } catch (e) {
    ElMessage.error('加载分类失败')
    categoryTreeData.value = []
  }
}

// 统一映射（确保字段存在）
const mapRecord = (r) => ({
  id: r.id || Math.random().toString(36).slice(2),
  date: r.date || r.adjustDate || '',
  productCode: r.productCode || r.code || '-',
  name: r.name || r.productName || '-',
  unit: r.unit || r.productUnit || '-',
  quantity: Number(r.quantity || 0),
  note: r.note || r.remark || '',
  userName: r.userName || r.updateUserName || '-',
  categoryId: r.categoryId || null
})

// 搜索/重置/分页
const handleSearch = () => {
  pagination.value.pageNum = 1;
  loadData()
}
const handleReset = () => {
  searchForm.productName = '';
  searchForm.categoryId = null;
  searchForm.dateRange = thisMonthRange();
  pagination.value.pageNum = 1;
  loadData()
}
const handleSizeChange = (size) => {
  pagination.value.pageSize = size;
  pagination.value.pageNum = 1;
  loadData()
}
const handleCurrentChange = (page) => {
  pagination.value.pageNum = page;
  loadData()
}

// 选择商品 & 新增记录
const openSelectProduct = () => {
  selectVisible.value = true
}
const handleProductSelected = (p) => {
  currentProductId.value = p?.id || null;
  selectVisible.value = false;
  if (p?.id) adjustVisible.value = true
}

const handleAdjustConfirm = async (payload) => {
  adjustVisible.value = false
  await addInventoryDetail(payload).then((res) => {
    if (res) {
      ElMessage.success('报损记录新增成功')
      handleSearch()
    }
  })
}

const computeIndex = (i) => (pagination.value.pageNum - 1) * pagination.value.pageSize + i + 1

onMounted(() => {
  searchForm.dateRange = thisMonthRange()
  tableData.value = {
  }
  loadCategoryTree()
  loadData()
})
</script>
<style scoped lang="scss">
.InventoryDamage {
  &-search {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid #eee;
  }

  &-search-left {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    align-items: center;
  }

  &-search-right {
    display: flex;
    gap: 8px;
    align-items: center;
  }

  &-search-item {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  &-search-item-label {
    width: 80px;
    color: #333;
    font-size: 14px;
    font-weight: 500;
    white-space: nowrap;
  }

  &-search-item-input {
    width: 220px;
  }

  &-table {
    padding: 16px 0;

    &-main {
      width: 100%;
    }
  }

  &-pagination {
    display: flex;
    justify-content: center;
    padding: 16px 0;
    border-top: 1px solid #eee;

    &-main {
      width: 100%;
    }
  }
}

.text-danger {
  color: #F56C6C;
}
</style>
